/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * SessionsDialog.java
 *
 * Created on 21-Sep-2011, 16:05:46
 */

package TimeRecording.forms;

import TimeRecording.TimeRecordingView;
import TimeRecording.business.FilteredQuery;
import TimeRecording.forms.renderers.CentredCellRenderer;
import TimeRecording.forms.renderers.DateCellRenderer;
import TimeRecording.forms.renderers.TimeCellRenderer;
import TimeRecording.tables.Employee;
import TimeRecording.tables.Session;
import TimeRecording.widgets.DaisyChainCalendar;
import TimeRecording.widgets.EmployeeComboBox;
import java.beans.Beans;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.swing.JOptionPane;
import javax.swing.table.TableCellRenderer;
import org.jdesktop.application.Action;
import org.jdesktop.observablecollections.ObservableCollections;

/**
 *
 * @author dpatchett
 */
public class SessionsDialog extends javax.swing.JDialog {

    private final static Logger LOGGER = Logger.getLogger(
            SessionsDialog.class.getName());

    private TimeRecordingView myParent;

    private final static int ALL_SESSIONS_ID = 0;
    private final static int THIS_YEARS_SESSIONS_ID = 1;
    private final static int PAST_SESSIONS_ID = 2;
    private final static int FUTURE_SESSIONS_ID = 3;
    private final static int CUSTOM_SESSIONS_ID = 4;

    private TableCellRenderer timeRenderer =
            new CentredCellRenderer(new TimeCellRenderer());

    private CentredCellRenderer centredRenderer = new CentredCellRenderer();
    
    private TableCellRenderer dateRenderer =
            new CentredCellRenderer(new DateCellRenderer());

    // <editor-fold defaultstate="collapsed" desc="recordSelected">
    protected boolean recordSelected = false;

    public boolean isRecordSelected() {
	return recordSelected;
    }

    public void setRecordSelected(boolean recordSelected) {

        boolean oldRecordSelected = this.recordSelected;
        this.recordSelected = recordSelected;
        firePropertyChange("recordSelected", oldRecordSelected, recordSelected);

    } // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="selectedSession">
    private Session selectedSession;

    public Session getSelectedSession() {
        return selectedSession;
    }

    public void setSelectedSession(Session selectedSession) {
        Session oldSelectedSession = this.selectedSession;
        this.selectedSession = selectedSession;
        firePropertyChange("selectedSession", oldSelectedSession, selectedSession);
        setRecordSelected(selectedSession != null);
    } // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="employeeFilterable">
    protected boolean employeeFilterable = false;

    public boolean isEmployeeFilterable() {
        return employeeFilterable;
    }

    public void setEmployeeFilterable(boolean employeeFilterable) {
        boolean oldEmployeeFilterable = this.employeeFilterable;
        this.employeeFilterable = employeeFilterable;
        firePropertyChange("employeeFilterable", oldEmployeeFilterable, employeeFilterable);
    } // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="filteredEmployee">
    protected Employee filteredEmployee;

    public Employee getFilteredEmployee() {
        return filteredEmployee;
    }

    public void setFilteredEmployee(Employee filteredEmployee) {
        Employee oldFilteredEmployee = this.filteredEmployee;
        this.filteredEmployee = filteredEmployee;
        firePropertyChange("filteredEmployee", oldFilteredEmployee, filteredEmployee);
    } // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="filteredStartDate">
    protected Date filteredStartDate;

    public Date getFilteredStartDate() {
        return filteredStartDate;
    }

    public void setFilteredStartDate(Date filteredStartDate) {
        Date oldFilteredStartDate = this.filteredStartDate;
        this.filteredStartDate = filteredStartDate;
        firePropertyChange("filteredStartDate", oldFilteredStartDate, filteredStartDate);
    } // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="filteredEndDate">
    protected Date filteredEndDate;

    public Date getFilteredEndDate() {
        return filteredEndDate;
    }

    public void setFilteredEndDate(Date filteredEndDate) {
        Date oldFilteredEndDate = this.filteredEndDate;
        this.filteredEndDate = filteredEndDate;
        firePropertyChange("filteredEndDate", oldFilteredEndDate, filteredEndDate);
    } // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="dateComboBeingActioned">

    protected boolean dateComboBeingActioned = false;

    public boolean getDateComboBeingActioned() {
        return dateComboBeingActioned;
    }

    public void setDateComboBeingActioned(boolean dateComboBeingActioned) {
        boolean oldDateComboBeingActioned = this.dateComboBeingActioned;
        this.dateComboBeingActioned = dateComboBeingActioned;
        firePropertyChange("dateComboBeingActioned",
                oldDateComboBeingActioned, dateComboBeingActioned);
    } // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="entityManager Getter & Setter">

    private EntityManager entityManager;
    
    public EntityManager getEntityManager() {
        return entityManager;
    }

    public void setEntityManager(EntityManager entityManager) {
        EntityManager oldEntityManager = this.entityManager;
        this.entityManager = entityManager;
        firePropertyChange("entityManager", oldEntityManager, entityManager);
    } // </editor-fold>

    /** Creates new form SessionsDialog */
    public SessionsDialog(TimeRecordingView parent,
            EntityManager entityManager, boolean modal) {

        super(parent.getFrame(), modal);

        myParent = parent;
        this.entityManager = entityManager;

        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        sessionList = ObservableCollections.observableList(new java.util.LinkedList());
        filterPanel = new javax.swing.JPanel();
        employeeCheck = new javax.swing.JCheckBox();
        employeeFilterCombo = new EmployeeComboBox(entityManager);
        dateFilterLabel = new javax.swing.JLabel();
        dateFilterCombo = new javax.swing.JComboBox();
        dateFilterFromLabel = new javax.swing.JLabel();
        dateFilterFrom = new com.toedter.calendar.JDateChooser();
        dateFilterToLabel = new javax.swing.JLabel();
        dateFilterTo = new com.toedter.calendar.JDateChooser();
        filterButton = new javax.swing.JButton();
        sessionPanel = new javax.swing.JScrollPane();
        sessionTable = new javax.swing.JTable();
        buttonPanel = new javax.swing.JPanel();
        newButton = new javax.swing.JButton();
        editButton = new javax.swing.JButton();
        deleteButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(TimeRecording.TimeRecordingApp.class).getContext().getResourceMap(SessionsDialog.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });
        getContentPane().setLayout(new java.awt.GridBagLayout());

        filterPanel.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createEmptyBorder(8, 8, 4, 8), javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("filterPanel.border.insideBorder.title")))); // NOI18N
        filterPanel.setName("filterPanel"); // NOI18N
        filterPanel.setLayout(new java.awt.GridBagLayout());

        employeeCheck.setText(resourceMap.getString("employeeCheck.text")); // NOI18N
        employeeCheck.setName("employeeCheck"); // NOI18N

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${employeeFilterable}"), employeeCheck, org.jdesktop.beansbinding.BeanProperty.create("selected"));
        bindingGroup.addBinding(binding);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(0, 8, 4, 4);
        filterPanel.add(employeeCheck, gridBagConstraints);

        employeeFilterCombo.setName("employeeFilterCombo"); // NOI18N
        employeeFilterCombo.setPreferredSize(new java.awt.Dimension(190, 20));

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${filteredEmployee}"), employeeFilterCombo, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
        bindingGroup.addBinding(binding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${employeeFilterable}"), employeeFilterCombo, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 33.0;
        gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 4);
        filterPanel.add(employeeFilterCombo, gridBagConstraints);

        dateFilterLabel.setText(resourceMap.getString("dateFilterLabel.text")); // NOI18N
        dateFilterLabel.setName("dateFilterLabel"); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(0, 8, 4, 4);
        filterPanel.add(dateFilterLabel, gridBagConstraints);

        dateFilterCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "All", "This Year", "Previous", "Future", "Custom" }));
        dateFilterCombo.setName("dateFilterCombo"); // NOI18N
        dateFilterCombo.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                dateFilterComboItemStateChanged(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 33.0;
        gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 4);
        filterPanel.add(dateFilterCombo, gridBagConstraints);

        dateFilterFromLabel.setText(resourceMap.getString("dateFilterFromLabel.text")); // NOI18N
        dateFilterFromLabel.setName("dateFilterFromLabel"); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(0, 8, 4, 4);
        filterPanel.add(dateFilterFromLabel, gridBagConstraints);

        dateFilterFrom.setMinimumSize(new java.awt.Dimension(150, 20));
        dateFilterFrom.setName("dateFilterFrom"); // NOI18N
        dateFilterFrom.setPreferredSize(new java.awt.Dimension(120, 20));

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${filteredStartDate}"), dateFilterFrom, org.jdesktop.beansbinding.BeanProperty.create("date"));
        bindingGroup.addBinding(binding);

        dateFilterFrom.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                dateFilterFromPropertyChange(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 33.0;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 4);
        filterPanel.add(dateFilterFrom, gridBagConstraints);

        dateFilterToLabel.setText(resourceMap.getString("dateFilterToLabel.text")); // NOI18N
        dateFilterToLabel.setName("dateFilterToLabel"); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 4;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(4, 8, 8, 4);
        filterPanel.add(dateFilterToLabel, gridBagConstraints);

        dateFilterTo.setMinimumSize(new java.awt.Dimension(150, 20));
        dateFilterTo.setName("dateFilterTo"); // NOI18N
        dateFilterTo.setPreferredSize(new java.awt.Dimension(120, 20));

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${filteredEndDate}"), dateFilterTo, org.jdesktop.beansbinding.BeanProperty.create("date"));
        bindingGroup.addBinding(binding);

        dateFilterTo.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                dateFilterToPropertyChange(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 5;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 33.0;
        gridBagConstraints.insets = new java.awt.Insets(4, 0, 8, 4);
        filterPanel.add(dateFilterTo, gridBagConstraints);

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(TimeRecording.TimeRecordingApp.class).getContext().getActionMap(SessionsDialog.class, this);
        filterButton.setAction(actionMap.get("applyFilter")); // NOI18N
        filterButton.setText(resourceMap.getString("filterButton.text")); // NOI18N
        filterButton.setName("filterButton"); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 6;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridheight = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.insets = new java.awt.Insets(0, 8, 8, 8);
        filterPanel.add(filterButton, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.weightx = 1.0;
        getContentPane().add(filterPanel, gridBagConstraints);

        sessionPanel.setName("sessionPanel"); // NOI18N

        sessionTable.setAutoCreateRowSorter(true);
        sessionTable.setName("sessionTable"); // NOI18N
        sessionTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, sessionList, sessionTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${startTime}"));
        columnBinding.setColumnName("Start Time");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${startTime}"));
        columnBinding.setColumnName("Start Time");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${endTime}"));
        columnBinding.setColumnName("End Time");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${hours}"));
        columnBinding.setColumnName("Hours");
        columnBinding.setColumnClass(Double.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${description}"));
        columnBinding.setColumnName("Description");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${employeeId}"));
        columnBinding.setColumnName("Employee Id");
        columnBinding.setColumnClass(TimeRecording.tables.Employee.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${selectedSession}"), sessionTable, org.jdesktop.beansbinding.BeanProperty.create("selectedElement"));
        bindingGroup.addBinding(binding);

        sessionPanel.setViewportView(sessionTable);
        sessionTable.getColumnModel().getColumn(0).setPreferredWidth(80);
        sessionTable.getColumnModel().getColumn(0).setMaxWidth(80);
        sessionTable.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("sessionTable.columnModel.title4")); // NOI18N
        sessionTable.getColumnModel().getColumn(0).setCellRenderer(dateRenderer);
        sessionTable.getColumnModel().getColumn(1).setPreferredWidth(80);
        sessionTable.getColumnModel().getColumn(1).setMaxWidth(80);
        sessionTable.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("sessionTable.columnModel.title0")); // NOI18N
        sessionTable.getColumnModel().getColumn(1).setCellRenderer(timeRenderer);
        sessionTable.getColumnModel().getColumn(2).setPreferredWidth(80);
        sessionTable.getColumnModel().getColumn(2).setMaxWidth(80);
        sessionTable.getColumnModel().getColumn(2).setHeaderValue(resourceMap.getString("sessionTable.columnModel.title1")); // NOI18N
        sessionTable.getColumnModel().getColumn(2).setCellRenderer(timeRenderer);
        sessionTable.getColumnModel().getColumn(3).setPreferredWidth(60);
        sessionTable.getColumnModel().getColumn(3).setMaxWidth(60);
        sessionTable.getColumnModel().getColumn(3).setHeaderValue(resourceMap.getString("sessionTable.columnModel.title5")); // NOI18N
        sessionTable.getColumnModel().getColumn(3).setCellRenderer(centredRenderer);
        sessionTable.getColumnModel().getColumn(4).setPreferredWidth(200);
        sessionTable.getColumnModel().getColumn(4).setHeaderValue(resourceMap.getString("sessionTable.columnModel.title2")); // NOI18N
        sessionTable.getColumnModel().getColumn(5).setPreferredWidth(150);
        sessionTable.getColumnModel().getColumn(5).setHeaderValue(resourceMap.getString("sessionTable.columnModel.title3")); // NOI18N

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        getContentPane().add(sessionPanel, gridBagConstraints);

        buttonPanel.setName("buttonPanel"); // NOI18N

        newButton.setAction(actionMap.get("newSession")); // NOI18N
        newButton.setText(resourceMap.getString("newButton.text")); // NOI18N
        newButton.setName("newButton"); // NOI18N
        buttonPanel.add(newButton);

        editButton.setAction(actionMap.get("editSession")); // NOI18N
        editButton.setText(resourceMap.getString("editButton.text")); // NOI18N
        editButton.setName("editButton"); // NOI18N
        buttonPanel.add(editButton);

        deleteButton.setAction(actionMap.get("deleteSession")); // NOI18N
        deleteButton.setText(resourceMap.getString("deleteButton.text")); // NOI18N
        deleteButton.setName("deleteButton"); // NOI18N
        buttonPanel.add(deleteButton);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;
        getContentPane().add(buttonPanel, gridBagConstraints);

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void dateFilterComboItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_dateFilterComboItemStateChanged

        setDateComboBeingActioned(true);

        int selection = dateFilterCombo.getSelectedIndex();

        if (selection == ALL_SESSIONS_ID) {
            dateFilterFrom.setDate(DaisyChainCalendar.START_OF_TIME);
            dateFilterTo.setDate(DaisyChainCalendar.END_OF_TIME);

        } else if (selection == THIS_YEARS_SESSIONS_ID) {
            dateFilterFrom.setDate(DaisyChainCalendar.startOfYear());
            dateFilterTo.setDate(DaisyChainCalendar.endOfYear());

        } else if (selection == PAST_SESSIONS_ID) {
            dateFilterFrom.setDate(DaisyChainCalendar.START_OF_TIME);
            dateFilterTo.setDate(DaisyChainCalendar.endOfToday());

        } else if (selection == FUTURE_SESSIONS_ID) {
            dateFilterFrom.setDate(DaisyChainCalendar.startOfToday());
            dateFilterTo.setDate(DaisyChainCalendar.END_OF_TIME);
        }

        setDateComboBeingActioned(false);
}//GEN-LAST:event_dateFilterComboItemStateChanged

    private void dateFilterFromPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_dateFilterFromPropertyChange
        if (!getDateComboBeingActioned()) {
            dateFilterCombo.setSelectedIndex(CUSTOM_SESSIONS_ID);
        }
}//GEN-LAST:event_dateFilterFromPropertyChange

    private void dateFilterToPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_dateFilterToPropertyChange
        if (!getDateComboBeingActioned()) {
            dateFilterCombo.setSelectedIndex(CUSTOM_SESSIONS_ID);
        }
}//GEN-LAST:event_dateFilterToPropertyChange

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened

        // Apply a default filter (this years holidays)

        setEmployeeFilterable(true);
        setFilteredEmployee(myParent.getLoggedInEmployee());

        dateFilterCombo.setSelectedIndex(THIS_YEARS_SESSIONS_ID);

        if (!Beans.isDesignTime()) {
            applyFilter();
        }
    }//GEN-LAST:event_formWindowOpened

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        myParent.hideSessionsDialog();
    }//GEN-LAST:event_formWindowClosing

    @Action
    @SuppressWarnings("unchecked")
    public void applyFilter() {

        // Build a custom query with all required filters

        FilteredQuery filterQuery = new FilteredQuery(Session.BASE_QUERY);

        if (employeeFilterable && filteredEmployee != null) {
            filterQuery.addClause(Session.EMPLOYEE_FILTER);
        }

        filterQuery.addClause(Session.DATE_FILTER);

        Query query = entityManager.createQuery(filterQuery.getQuery());

        if (employeeFilterable && filteredEmployee != null) {
            query.setParameter(
                    Session.COL_EMPLOYEE_ID,
                    filteredEmployee);
        }

        query.setParameter(
                Session.COL_LOWER_DATE,
                filteredStartDate);

        query.setParameter(
                Session.COL_UPPER_DATE,
                filteredEndDate);

        sessionList.clear();
        sessionList.addAll(query.getResultList());
    }

    @Action
    public void newSession() {

        Session session = new Session();

        SessionEditor editor = new SessionEditor(this);
        editor.setSession(session);
        editor.setVisible(true);
        if (!editor.isSaveSelected()) {
            return;
        }

        try {
            // Plumb in the correct user (one used in dialog probably stale)

            Employee employee = entityManager.find(Employee.class,
                    session.getEmployeeId().getEmployeeId());

            session.setEmployeeId(employee);

            // Ensure the holiday adjustment is plugged into the employee's details

            employee.getSessions().add(session);

            entityManager.getTransaction().begin();
            entityManager.persist(session);

            entityManager.getTransaction().commit();
            entityManager.refresh(session.getEmployeeId());

            sessionList.add(session);
            int row = sessionList.size() - 1;
            sessionTable.setRowSelectionInterval(row, row);
            sessionTable.scrollRectToVisible(sessionTable.getCellRect(row, 0, true));

        } catch (RuntimeException e) {
            LOGGER.log(Level.SEVERE, "Error creating session", e);
            if (entityManager.getTransaction().isActive()) {
                entityManager.getTransaction().rollback();
            }
            ErrorDialog.showError(this, e);
        }
    }

        @Action(enabledProperty = "recordSelected")
    public void editSession() {

        SessionEditor editor = new SessionEditor(this);
        editor.setSession(selectedSession);
        editor.setVisible(true);
        if (!editor.isSaveSelected()) {
            return;
        }

        try {
            entityManager.getTransaction().begin();
            entityManager.merge(selectedSession);

            entityManager.getTransaction().commit();

        } catch (RuntimeException e) {
            LOGGER.log(Level.SEVERE, "Error updating session", e);
            if (entityManager.getTransaction().isActive()) {
                entityManager.getTransaction().rollback();
            }
            ErrorDialog.showError(this, e);
        }
    }

        @Action(enabledProperty = "recordSelected")
    public void deleteSession() {

        int choice = JOptionPane.showConfirmDialog(this,
                "Are you sure you wish to delete the session",
                "Delete Session", JOptionPane.YES_NO_OPTION);

        if (choice == JOptionPane.NO_OPTION) {
            return;
        }

        Session session = sessionList.get(
                sessionTable.convertRowIndexToModel(
                        sessionTable.getSelectedRow()));

        try {
            entityManager.getTransaction().begin();

            // Delete the actual holiday
            session.getEmployeeId().getSessions().remove(session);
            entityManager.remove(session);

            // Complete the transaction
            entityManager.getTransaction().commit();

            // Assume that no exceptions were thrown, remove the holiday from the GUI
            sessionList.remove(session);

            entityManager.refresh(session.getEmployeeId());

        } catch (RuntimeException e) {
            LOGGER.log(Level.SEVERE, "Error deleting session", e);
            if (entityManager.getTransaction().isActive()) {
                entityManager.getTransaction().rollback();
            }
            ErrorDialog.showError(this, e);
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel buttonPanel;
    private javax.swing.JComboBox dateFilterCombo;
    private com.toedter.calendar.JDateChooser dateFilterFrom;
    private javax.swing.JLabel dateFilterFromLabel;
    private javax.swing.JLabel dateFilterLabel;
    private com.toedter.calendar.JDateChooser dateFilterTo;
    private javax.swing.JLabel dateFilterToLabel;
    private javax.swing.JButton deleteButton;
    private javax.swing.JButton editButton;
    private javax.swing.JCheckBox employeeCheck;
    private javax.swing.JComboBox employeeFilterCombo;
    private javax.swing.JButton filterButton;
    private javax.swing.JPanel filterPanel;
    private javax.swing.JButton newButton;
    private java.util.List<TimeRecording.tables.Session> sessionList;
    private javax.swing.JScrollPane sessionPanel;
    private javax.swing.JTable sessionTable;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

}
